import { defineStore } from 'pinia'
import { ref } from 'vue'

export const user_Store = defineStore('user_info', () => {
  let user_token = ref();
  let user_info = ref();
  let user_life_data = ref();
  let first_login = ref(true);

  // Broadcast Channel
  let userStoreChannel = null;

  // 初始化 Broadcast Channel
  const initializeBroadcastChannel = () => {
    if (!userStoreChannel) {
      userStoreChannel = new BroadcastChannel('user_store_channel');
      userStoreChannel.addEventListener('message', (event) => {
        const { type, payload } = event.data;
        try {
          switch (type) {
            case 'RESET_USER_STORE':
              user_token.value = null;
              user_info.value = null;
              break;
            case 'UPDATE_USER_INFO':
              if (payload.data != undefined) { 
                 user_info.value = JSON.parse(payload.data);
              }
              break;
            case 'UPDATE_USER_INFO_BY_KEY':
              user_info.value[payload.key] = JSON.parse(payload.value);
              break;
          }
        } catch (error) {
          
        }
      });
    }
  };

  // 确保初始化（仅在必要时调用）
  const ensureBroadcastChannelInitialized = () => {
    if (!userStoreChannel) {
      initializeBroadcastChannel();
    }
  };

  // 初始化仓库逻辑
  const initStore = () => {
    console.log('Initializing store...');
    ensureBroadcastChannelInitialized(); // 确保广播通道初始化
    syncAllFields(); // 同步所有字段到其他窗口
  };

  // 设置用户信息
  const set_user_info = function (data, initialize = true) {
    if (initialize) ensureBroadcastChannelInitialized();
    user_info.value = data;
    syncAllFields(data);
  };

  const set_u_tk = function (token, initialize = true) {
    if (initialize) ensureBroadcastChannelInitialized();
    user_token.value = token;
    // syncAllFields();
  };

  const get_user_tk = function (initialize = false) {
    if (initialize) ensureBroadcastChannelInitialized();
    return user_token.value;
  };

  const get_user = function (initialize = false) {
    if (initialize) ensureBroadcastChannelInitialized();
    return user_info.value;
  };

  const get_user_life_data = function (func, id, initialize = false) {
    if (initialize) ensureBroadcastChannelInitialized();
    if (func && id) {
      return func(user_life_data.value, id);
    }
    return user_life_data.value;
  };

  const set_user_life_data = function (data, initialize = true) {
    if (initialize) ensureBroadcastChannelInitialized();
    user_life_data.value = data;
    syncAllFields(data);
  };

  const set_user_info_by_key = function (key, value, initialize = true) {
    if (initialize) ensureBroadcastChannelInitialized();
    user_info.value[key] = value;
    syncKeyFields('UPDATE_USER_INFO_BY_KEY',key,value)
    // syncAllFields();
  };

  const set_user_isfirstlogin = function (initialize = true) {
    if (initialize) ensureBroadcastChannelInitialized();
    first_login.value = false;
    // syncAllFields();
  };

  const get_user_isfirstlogin = function (initialize = false) {
    if (initialize) ensureBroadcastChannelInitialized();
    return first_login.value;
  };

  const reset_userstore = function (options = {}, initialize = true) {
    if (initialize) ensureBroadcastChannelInitialized();
    user_token.value = null;
    user_info.value = null;
    user_life_data.value = null;
    first_login.value = true;

    if (options.broadcast !== false) {
      userStoreChannel.postMessage({
        type: 'RESET_USER_STORE',
        payload: {},
      });
    }
  };

  const cleanupUserStoreListener = () => {
    userStoreChannel?.close();
    userStoreChannel = null;
  };

  const syncAllFields = (data) => {
    ensureBroadcastChannelInitialized();
    userStoreChannel.postMessage({
      type: 'UPDATE_USER_INFO',
      payload: {data:JSON.stringify(data)},
    });
  };
  const syncKeyFields = (info,key,data) => {
    ensureBroadcastChannelInitialized();
    userStoreChannel.postMessage({
      type: info,
      payload: {key,data:JSON.stringify(data)},
    });
  };

 

  // 在仓库初始化时调用
  initStore();

  return {
    set_user_life_data,
    user_info,
    user_life_data,
    first_login,
    set_u_tk,
    get_user_tk,
    get_user,
    get_user_life_data,
    set_user_info,
    get_user_isfirstlogin,
    set_user_isfirstlogin,
    set_user_info_by_key,
    reset_userstore,
    cleanupUserStoreListener,
    initializeBroadcastChannel,
    ensureBroadcastChannelInitialized,
    syncAllFields,
  }
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user_info',
        storage: sessionStorage,
        paths: ['user_info']
      },
      {
        key: 'first_login',
        storage: sessionStorage,
        paths: ['first_login']
      },
    ]
  }
}
);